package com.hue.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.hue.realm.ShiroRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/*
    shiro的配置类
 */
@Configuration
@MapperScan("com.hue.mapper")
public class ShiroConfig {
    //1.创建ShiroFilterFactoryBean
    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager securityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        //添加安全管理器
        shiroFilterFactoryBean.setSecurityManager(securityManager);
        //添加Shiro内置过滤器，实现权限相关的拦截
        /*
            常用的过滤器：
                1.anon:不需要认证就可以访问
                2.authc:必须认证才能访问
                3.user:如果使用rememberMe功能可以直接访问
                4.perms:该资源必须得到资源权限才能访问
                5.roles:该资源必须得到角色权限才能访问
         */
        Map<String, String> map = new HashMap<>();
        //设置资源必须认证后才能访问
//        map.put("/user/*", "authc");
        //设置必须认证并且授权才能访问的资源
        map.put("/user/add", "perms[user:add]");
        map.put("/user/update", "perms[user:update]");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        //设置登录页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        //设置未授权时跳转的资源
        shiroFilterFactoryBean.setUnauthorizedUrl("/user/authorized");
        return shiroFilterFactoryBean;
    }

    //2.创建DefaultWebSecurityManager
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(ShiroRealm shiroRealm) {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        //添加Realm
        securityManager.setRealm(shiroRealm);
        return securityManager;
    }

    //3.创建Realm
    @Bean
    public ShiroRealm shiroRealm() {
        return new ShiroRealm();
    }

    //thymeleaf支持shiro标签的配置
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
